var api = require('../../../config/api.js');
var util = require('../../../utils/util.js');
var user = require('../../../utils/user.js');

var app = getApp();
Page({
  data: {
    username: '',
    password: '',
    password2: '',
    code: '',
    loginErrorCount: 0,
    isLoginMode: true,
    codePath: '',
    loginAfterAction: 'userCenter'
  },
  onLoad: function(options) {
    // 页面初始化 options为页面跳转所带来的参数
    // 页面渲染完成
    if(options.action){
      this.setData({
        loginAfterAction: options.action
      })
    }
    console.log(this.data.loginAfterAction)

  },
  onReady: function() {

  },

  changeLoginMode: function(){
    var that = this
    that.refreshCode()
    this.setData({
      isLoginMode: !that.data.isLoginMode
    })
  },

  refreshCode(){
    var that = this
    wx.downloadFile({
      url: 'https://register-pub.com/check_code.php', //仅为示例，并非真实的资源
      success (res) {
        console.log(res)
        // 只要服务器有响应数据，就会把响应内容写入文件并进入 success 回调，业务需要自行判断是否下载到了想要的内容
        if (res.statusCode === 200) {
          var cookie = res.cookies[0]
          wx.setStorageSync('cookie', cookie)
          console.log(res.tempFilePath)
          that.setData({
            codePath: res.tempFilePath
          })
          
        }
      }
    })
    
  },
  onShow: function() {
      // 页面显示
      var that = this
      setTimeout(()=>{
        that.refreshCode()
      },500)
      
  },
  onHide: function() {
    // 页面隐藏

  },
  onUnload: function() {
    // 页面关闭

  },

  checkInput: function(){
    console.log(this.data.username)
    if(this.data.username.length < 5){
      return '用户名至少5个字符';
    }
    if ((/[^\w_]/g.test(this.data.username))) {
        return '用户名只能输入小写字母、数字、下划线';
    }

    if(this.data.password.length < 6 || this.data.password.length>18){
      return '密码长度请在6到18位之间';
    }
    if ((/[^\w_]/g.test(this.data.password))) {
        return '密码只能输入小写字母、数字、下划线';
    }
    return null;
  },

  accountLogin: function() {
    var that = this;
    var checkInputMsg = this.checkInput()

    if(checkInputMsg!=null){
      wx.showModal({
        title: '错误信息',
        content: checkInputMsg,
        showCancel: false
      });
      return false;
    }

    wx.showLoading({
      title: "登录中",
      mask: true
    });

    var userInfo = {
      account: that.data.username,
      password: that.data.password,
      password2: that.data.password2,
      is_login_mode: that.data.isLoginMode?'true':'false',
      code_char: this.data.code
    }

    wx.request({
      url: 'https://register-pub.com/user_register-api.php',
      header:{
        'Cookie': wx.getStorageSync('cookie')
      },
      data: userInfo,
      method: 'POST',
      
      success: function(res) {
        wx.hideLoading();
        var cookie = res.cookies[0]
        console.log(cookie)
        console.log(res.data)
        wx.setStorageSync('userInfo', JSON.stringify(userInfo))

        if (res.data.code == 0) {
          that.setData({
            loginErrorCount: 0
          });
          app.globalData.hasLogin = true;
          
          var msg = that.data.isLoginMode?'登录成功跳转中':'注册成功跳转中'
          wx.showLoading({
            title: msg,
            mask: true
          });
          setTimeout(()=>{
            wx.hideLoading();
            if(that.data.loginAfterAction=='softProject'){
              wx.navigateBack()
            }else{
              wx.switchTab({
                url: '/pages/ucenter/index/index'
              });
            }
          },3000)
          
          
        } else {
          that.setData({
            loginErrorCount: that.data.loginErrorCount + 1
          });
          app.globalData.hasLogin = false;
          util.showErrorToast(res.data.message);
          that.refreshCode()
        }
      },
      fail: function(){
        util.showErrorToast('网络异常');
      }
    });
  },
  bindUsernameInput: function(e) {

    this.setData({
      username: e.detail.value
    });
  },
  bindPasswordInput: function(e) {

    this.setData({
      password: e.detail.value
    });
  },
  bindPasswordInput2: function(e) {

    this.setData({
      password2: e.detail.value
    });
  },
  bindCodeInput: function(e) {

    this.setData({
      code: e.detail.value
    });
  },
  clearInput: function(e) {
    switch (e.currentTarget.id) {
      case 'clear-username':
        this.setData({
          username: ''
        });
        break;
      case 'clear-password':
        this.setData({
          password: ''
        });
        break;
      case 'clear-password2':
        this.setData({
          password2: ''
        });
        break;
      case 'clear-code':
        this.setData({
          code: ''
        });
        break;
    }
  }
})